package com.gitee.sop.layui.adminserver.module.background.develop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.sop.layui.adminserver.module.background.admin.service.SysDataModifyLockService;
import com.gitee.sop.layui.adminserver.module.background.admin.util.SysDataModifyLockUtil;
import com.gitee.sop.layui.adminserver.module.background.develop.entity.SysFunctionRole;
import com.gitee.sop.layui.adminserver.module.background.develop.entity.SysFunctionRoleRelation;
import com.gitee.sop.layui.adminserver.module.background.develop.manager.SysFunctionRoleManager;
import com.gitee.sop.layui.adminserver.module.background.develop.manager.SysFunctionRoleRelationCacheManager;
import com.gitee.sop.layui.adminserver.module.background.develop.mapper.SysFunctionRoleRelationMapper;
import com.gitee.sop.layui.adminserver.module.background.develop.service.SysFunctionRoleRelationService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author admin
 * @since 2019-11-27
 */
@Service
public class SysFunctionRoleRelationServiceImpl extends ServiceImpl<SysFunctionRoleRelationMapper, SysFunctionRoleRelation> implements SysFunctionRoleRelationService {

    @Lazy
    @Resource
    private SysFunctionRoleRelationCacheManager sysFunctionRoleCacheManager;

    @Lazy
    @Resource
    private SysFunctionRoleManager sysFunctionRoleManager;

    @Lazy
    @Resource
    private SysDataModifyLockService sysDataModifyLockService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setAuthority(Integer roleId, List<Integer> fnIdList) {
        sysDataModifyLockService.checkLocked(SysDataModifyLockUtil.generateKey(SysFunctionRole.class, roleId + ""));

        //删除已存在的映射关系
        sysFunctionRoleCacheManager.removeByRoleIdAndCreatedUuid(roleId);
        if (!fnIdList.isEmpty()) {
            //TODO 检索功能id权限，防止恶意攻击，刷取功能权限

            List<SysFunctionRoleRelation> list = fnIdList.stream().collect(ArrayList::new, (res, ele) -> res.add(new SysFunctionRoleRelation(roleId, ele)), (l, r) -> {
            });
            saveBatch(list);

            sysFunctionRoleManager.clearCache();
        }
    }

    @Override
    public List<Integer> listFunctionIdByFunctionRoleId(Integer functionRoleId) {
        return this.baseMapper.selectFunctionIdByRoleId(functionRoleId);
    }

    @Override
    public List<String> listFunctionNameByFunctionId(int functionId) {
        return sysFunctionRoleCacheManager.listFunctionNameByFunctionId(functionId);
    }

    @Override
    public int countInFunctionRoleIdList(List<Integer> functionRoleIdList) {
        return baseMapper.countInRoleIdList(functionRoleIdList);
    }
}
